HC-SR04 sensor

Note: You need two resistors, one of about 1KOhm and one 2KOhm; the 1KOhm resistor connect the ECHO pin to the GPIO measuring pin (GPio 24), or between the two yellow wires in the drawing, while the 2KOhm makes the connection between the GPIO pin and GND (yellow to black)


In [ ]:
#We will use "RPi.GPIO" and "time" Python libraries in our code
import RPi.GPIO as GPIO
import time

#Set BCM numbering gebruiken for the Raspberry Pi GPIO pins (cfr numbers on the case)
GPIO.setmode(GPIO.BCM)

#Set the "trigger" pin value for the ultrasonic sensor, which is connected to pin 23
TRIG = 23
#Set the "echo" pin value for the ultrasonic sensor, which is connected to pin 24
ECHO = 24

#Set the pin mode to "output" for the trigger pin and "input" for the echo pin
#This way the Raspberry Pi can send a trigger signal and read the echo
GPIO.setup(TRIG,GPIO.OUT)
GPIO.setup(ECHO,GPIO.IN)

In [ ]:
#turn off trigger signal for 2 seconds to prevent disturbances
#(i.e. set trigger pin -number 23- for 2 seconds to 0 volts)
print("Sensor stabilization")
GPIO.output(TRIG, 0)
time.sleep(2)

#send a 10 microsecond trigger signal
GPIO.output(TRIG, 1)
time.sleep(0.00001)
GPIO.output(TRIG, 0)

#record the start and end times of the returning signal on the echo port to measure its length  
tijd opnemen zolang het echo signaal uit staat en opslaan in de pulse_start variabele
pulse_start = time.time()
while GPIO.input(ECHO)==0:
  pulse_start = time.time()

while GPIO.input(ECHO)==1:
  pulse_end = time.time()

#The resulting length is directly related to the distance to the detected object
pulse_duration = pulse_end - pulse_start

#calculate and print the distance in cm
distance = pulse_duration * 17150
print("Measured distance: {0:.2f} cm".format(distance))

In [ ]:
#reinitialize GPIO pins
GPIO.cleanup()